<!doctype html>
<html lang="zh-cn">
<head>

    <meta charset="utf-8">
    <meta name="generator" content="Hugo 0.57.2" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Java8time | The Sky of OtsWang</title>
    <meta property="og:title" content="Java8time - The Sky of OtsWang">
    <meta property="og:type" content="article">
        
    <meta property="article:published_time" content="2019-05-30T09:57:14&#43;08:00">
        
        
    <meta property="article:modified_time" content="2019-05-30T09:57:14&#43;08:00">
        
    <meta name="Keywords" content="golang,go语言,otswang,java,博客,python">
    <meta name="description" content="Java8time">
        
    <meta name="author" content="OtsWang">
    <meta property="og:url" content="https://otswang.gitee.io/hugo/post/java/java-checklist/">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="/hugo/css/normalize.css">
    
        <link rel="stylesheet" href="/hugo/css/prism.css">
    
    <link rel="stylesheet" href="/hugo/css/style.css">
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

    


    
    
</head>

<body>
<header id="header" class="clearfix">
    <div class="container">
        <div class="col-group">
            <div class="site-name ">
                
                    <a id="logo" href="https://otswang.gitee.io/hugo/">
                        The Sky of OtsWang
                    </a>
                
                <p class="description">擅长写HelloWorld的小小码农</p>
            </div>
            <div>
                <nav id="nav-menu" class="clearfix">
                    
                    
                    <a  href="https://otswang.gitee.io/hugo/" title="Home">Home</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/tags/" title="Tags">Tags</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/categories/" title="Categories">Categories</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/archives/" title="Archives">Archives</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/about/" title="About">About</a>
                    
                </nav>
            </div>
        </div>
    </div>
</header>


<div id="body">
    <div class="container">
        <div class="col-group">

            <div class="col-8" id="main">
                <div class="res-cons">
                    <article class="post">
                        <header>
                            <h1 class="post-title">Java8time</h1>
                        </header>
                        <date class="post-meta meta-date">
                            2019年5月30日
                        </date>
                        
                        <div class="post-meta">
                            <span>|</span>
                            
                                <span class="meta-category"><a href="https://otswang.gitee.io/hugo/categories/java">Java</a></span>
                            
                        </div>
                        
                        
                        
                        <div class="post-content">
                            <p>Java8 中对于时间处理的新添加的类学习。</p>

<h2 id="概括">概括</h2>

<p>主要的类有： <code>LocalDate, LocalTime, LocalDateTime, Instant, Duration, Period, DateTimeFormatter, TemporalAdjuster</code>等。</p>

<h2 id="localedate-与-localedatetime">LocaleDate 与 LocaleDateTime</h2>

<pre><code class="language-java">/**
* LocaleDateTime
*/
@Test
public void test01() {
    LocalDateTime now = LocalDateTime.now();

    System.out.println(now);

    now = LocalDateTime.of(2019, 5, 30, 12, 10, 10);

    System.out.println(now);

    now = now.plus(2, ChronoUnit.DAYS);

    System.out.println(now);

    System.out.println(String.format(&quot;%d%d%d&quot;, now.getYear(),now.getHour(), now.getSecond()));
}

</code></pre>

<h2 id="instant">Instant</h2>

<pre><code class="language-java">/**
* Instant 立即的
*/
@Test
public void test02() {
    Instant now = Instant.now();
    System.out.println(now + &quot;\n&quot; + now.toEpochMilli() + &quot;\n&quot; + System.currentTimeMillis());

    now = Instant.now().atOffset(ZoneOffset.ofHours(8)).toInstant();

    System.out.println(now + &quot;\n&quot; + now.toEpochMilli() + &quot;\n&quot; + System.currentTimeMillis());
}
</code></pre>

<h2 id="duration">Duration</h2>

<pre><code class="language-java">/**
* Duration
*/
@Test
public void test03() {
    Instant now1 = Instant.now();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e){
        e.printStackTrace();
    }
    Instant now2 = Instant.now();

    System.out.println(Duration.between(now1, now2).getSeconds());


    Instant now3 = Instant.now();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e){
        e.printStackTrace();
    }
    Instant now4 = Instant.now().atOffset(ZoneOffset.ofHours(8)).toInstant();

    System.out.println(Duration.between(now3, now4).getSeconds());
}
</code></pre>

<h2 id="period">Period</h2>

<pre><code class="language-java">/**
* Period
*/
@Test
public void test04() {
    LocalDate date1 = LocalDate.now();
    LocalDate date2 = LocalDate.now().plusDays(1);
    System.out.println(Period.between(date1, date2).get(ChronoUnit.DAYS));

    LocalDateTime dateTime1 = LocalDateTime.now();
    LocalDateTime dateTime2 = LocalDateTime.now().plusDays(1);
    System.out.println(Duration.between(dateTime1, dateTime2).get(ChronoUnit.SECONDS));

    LocalTime now = LocalTime.now();
    LocalTime other = LocalTime.of(23, 59, 59);
    System.out.println(now + &quot;--&quot; + other);
    long secondes = Duration.between(other, now).abs().get(ChronoUnit.SECONDS);
    System.out.println(secondes + &quot;:&quot; + secondes / 3600.0);


}
</code></pre>

<h2 id="temporaladjuster">TemporalAdjuster</h2>

<pre><code class="language-java">/**
* TemporalAdjuster
*/
@Test
public void test05() {
    LocalDateTime now = LocalDateTime.now();
    System.out.println(now.with(TemporalAdjusters.firstDayOfMonth()));

    LocalDateTime nextWorkDay = now.with(temporal -&gt; {
        LocalDateTime other = (LocalDateTime) temporal;
        DayOfWeek dow = other.getDayOfWeek();
        if (dow.equals(DayOfWeek.FRIDAY)){
            return now.plusDays(3);
        } else if (dow.equals(DayOfWeek.SATURDAY)){
            return now.plusDays(2);
        } else {
            return now.plusDays(1);
        }
    });

    System.out.println(nextWorkDay.getDayOfWeek());
}
</code></pre>

<h2 id="format">Format</h2>

<pre><code class="language-java">/**
* format
*/
@Test
public void test06() {

    LocalDate now = LocalDate.now();
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&quot;);
    String now_str = now.format(dtf);
    System.out.println(now_str);
    LocalDate now_2 = LocalDate.parse(now_str, dtf);
    System.out.println(now_2);

}
</code></pre>

<h2 id="format线程安全">Format线程安全</h2>

<pre><code class="language-java">@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
                            FieldPosition pos)
{
//  如此轻易地使用内部变量，肯定不能线程安全
//  线程都对pos进行写操作，必然会影响其他线程的读操作
    pos.beginIndex = pos.endIndex = 0;
    return format(date, toAppendTo, pos.getFieldDelegate());
}

private StringBuffer format(Date date, StringBuffer toAppendTo,
                            FieldDelegate delegate) {
    // Convert input date to time field list
    // 这里已经彻底毁坏线程的安全性
    calendar.setTime(date);

    boolean useDateFormatSymbols = useDateFormatSymbols();

    for (int i = 0; i &lt; compiledPattern.length; ) {
        int tag = compiledPattern[i] &gt;&gt;&gt; 8;
        int count = compiledPattern[i++] &amp; 0xff;
        if (count == 255) {
            count = compiledPattern[i++] &lt;&lt; 16;
            count |= compiledPattern[i++];
        }

        switch (tag) {
        case TAG_QUOTE_ASCII_CHAR:
            toAppendTo.append((char)count);
            break;

        case TAG_QUOTE_CHARS:
            toAppendTo.append(compiledPattern, i, count);
            i += count;
            break;

        default:
            subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
            break;
        }
    }
    return toAppendTo;
}
</code></pre>

<pre><code class="language-java">public String format(TemporalAccessor temporal) {
    StringBuilder buf = new StringBuilder(32);
    formatTo(temporal, buf);
    return buf.toString();
}

public void formatTo(TemporalAccessor temporal, Appendable appendable) {
    Objects.requireNonNull(temporal, &quot;temporal&quot;);
    Objects.requireNonNull(appendable, &quot;appendable&quot;);
    try {
        DateTimePrintContext context = new DateTimePrintContext(temporal, this);
        if (appendable instanceof StringBuilder) {
            printerParser.format(context, (StringBuilder) appendable);
        } else {
            // buffer output to avoid writing to appendable in case of error
            StringBuilder buf = new StringBuilder(32);
            printerParser.format(context, buf);
            appendable.append(buf);
        }
    } catch (IOException ex) {
        throw new DateTimeException(ex.getMessage(), ex);
    }
}

public boolean format(DateTimePrintContext context, StringBuilder buf) {
    int length = buf.length();
    if (optional) {
        context.startOptional();
    }
    try {
        for (DateTimePrinterParser pp : printerParsers) {
            if (pp.format(context, buf) == false) {
                buf.setLength(length);  // reset buffer
                return true;
            }
        }
    } finally {
        if (optional) {
            context.endOptional();
        }
    }
    return true;
}

private final CompositePrinterParser printerParser;
</code></pre>
                        </div>

                        


                        


                        <div class="post-meta meta-tags">
                            
                            <ul class="clearfix">
                                
                                <li><a href="https://otswang.gitee.io/hugo/tags/%E6%97%B6%E9%97%B4%E7%B1%BB">时间类</a></li>
                                
                            </ul>
                            
                        </div>
                    </article>
                    
    

    
    
                </div>
            </div>
            <div id="secondary">

    <section class="widget">
        <form id="search" action="//www.google.com/search" method="get" accept-charset="utf-8" target="_blank" _lpchecked="1">
      
      <input type="text" name="q" maxlength="20" placeholder="Search">
      <input type="hidden" name="sitesearch" value="https://otswang.gitee.io/hugo/">
      <button type="submit" class="submit icon-search"></button>
</form>
    </section>

    
    <div class="clear">
        <div class="toc-article">
            <div class="toc-title">文章目录</dixsv>
            <nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#概括">概括</a></li>
<li><a href="#localedate-与-localedatetime">LocaleDate 与 LocaleDateTime</a></li>
<li><a href="#instant">Instant</a></li>
<li><a href="#duration">Duration</a></li>
<li><a href="#period">Period</a></li>
<li><a href="#temporaladjuster">TemporalAdjuster</a></li>
<li><a href="#format">Format</a></li>
<li><a href="#format线程安全">Format线程安全</a></li>
</ul></li>
</ul>
</nav>
        </div>
    </div>
    

</div>
        </div>
    </div>
</div>
<footer id="footer">
    <div class="container">
        &copy; 2020 <a href="https://otswang.gitee.io/hugo/">The Sky of OtsWang By OtsWang</a>.
        Powered by <a rel="nofollow noreferer noopener" href="https://gohugo.io" target="_blank">Hugo</a>.
        <a href="https://www.flysnow.org/" target="_blank">Theme</a> based on <a href="https://github.com/Dudiao137/maupassant-hugo" target="_blank">maupassant-ots</a>.
        
    </div>
</footer>


    <script type="text/javascript">
    
    (function(){
        $("pre code").parent().addClass("line-numbers")
    }())

    window.MathJax = {
        tex2jax: {
            inlineMath: [ ['$','$'] ],
            processEscapes: true
        }
    };
    </script>
    <script type="text/javascript" src="/hugo/js/prism.js" async="true"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>

<a id="rocket" href="#top"></a>
<script type="text/javascript" src="/hugo/js/totop.js?v=0.0.0" async=""></script>







 
 <script src="https://mermaidjs.github.io/scripts/mermaid.min.js"></script>
 <script>
       mermaid.initialize({ startOnLoad: true });
 </script>
</body>
</html>
